/**
 * Copyright (c) 2017, Alex. All rights reserved.
 */
package com.oschina.bottle.redis.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * redis锁实现
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2017/11/14
 * @since 1.0
 */
public abstract class AbstractRedisLock implements Lock
{

    /**
     * 这里需不需要保证可见性值得讨论, 因为是分布式的锁,
     * 1.同一个jvm的多个线程使用不同的锁对象其实也是可以的, 这种情况下不需要保证可见性
     * 2.同一个jvm的多个线程使用同一个锁对象, 那可见性就必须要保证了.
     */
    protected volatile boolean locked;

    /**
     * 持有该锁的线程
     */
    private Thread ownerThread;

    @Override
    public void lock()
    {
        try
        {
            lock(false, 0, null, false);
        } catch (InterruptedException ex) {
            //ignore
        }
    }

    @Override
    public void lockInterruptibly()
        throws InterruptedException
    {
        lock(false, 0, null, false);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit)
    {
        try {
            return lock(true, time, unit, false);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("" + e);
        }
        return false;
    }

    @Override
    public void unlock()
    {
        // TODO 检查当前线程是否持有锁
        if (Thread.currentThread() != getOwnerThread()) {
            throw new IllegalMonitorStateException("current thread does not hold the lock");
        }

        unlock0();
        setOwnerThread(null);
    }

    protected abstract void unlock0();

    /**
     * 阻塞式获取锁的实现
     *
     * @param useTimeout
     * @param time
     * @param unit
     * @param interrupt
     *            是否响应中断
     * @return
     * @throws InterruptedException
     */
    protected abstract boolean lock(boolean useTimeout, long time, TimeUnit unit, boolean interrupt)
        throws InterruptedException;

    public Thread getOwnerThread()
    {
        return ownerThread;
    }

    public void setOwnerThread(Thread ownerThread)
    {
        this.ownerThread = ownerThread;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }
}
